/*
Copyright 2008  Four Roads LLC conact@4-roads.com

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either 
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections;
using System.IO;
using System.Security;
using System.Text.RegularExpressions;
using CommunityServer.Components;
using CommunityServer.ControlPanel;
using CommunityServer.ControlPanel.Controls;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using CA = ComponentArt.Web.UI;
using Group = CommunityServer.Components.Group;
using ResourceControl = CommunityServer.ControlPanel.Controls.ResourceControl;

namespace FourRoads.Links.Controls
{
		/// <summary>
		///		Summary description for GroupTreeViewControl.
		/// </summary>
		public class GroupTreeViewControl : BaseControl
		{

			protected string AjaxQueryStringKey
			{
				get
				{
					return "___" + this.ClientID;
				}
			}

			#region Child Controls
			protected ContextMenu SectionContextMenu;
			protected CA.TreeView Tree;
			#endregion

			private string addSectionButtonClientID;
			public string AddSectionButtonClientID
			{
				get{return addSectionButtonClientID;}
				set{addSectionButtonClientID = value;}
			}

			private string deleteButtonClientID;
			public string DeleteButtonClientID
			{
				get{return deleteButtonClientID;}
				set{deleteButtonClientID = value;}
			}

		
			protected string AjaxQueryStringValue = "{0}";
			protected string AjaxQueryStringValuePattern = "(\\d+):([\\w\\.-]*)";
			private bool IsAdministrator = false;
			protected ResourceControl Resourcecontrol1;

			private void Page_Load(object sender, EventArgs e)
			{
				if (this.Page.Request.QueryString[AjaxQueryStringKey] != null)
					HandleXmlRequest(this.Page.Request.QueryString[AjaxQueryStringKey]);

				AjaxManager.Register(this,"GroupTreeViewControl");

				IsAdministrator = ExtendedUserRoles.IsLinkAdministrator;

				if(!Page.IsPostBack)
				{
					EnsureChildControls();
					BuildSectionTree();
				}
			}

			#region Web Form Designer generated code
			override protected void OnInit(EventArgs e)
			{
				//
				// CODEGEN: This call is required by the ASP.NET Web Form Designer.
				//
				InitializeComponent();
				base.OnInit(e);
			}
		
			/// <summary>
			///		Required method for Designer support - do not modify
			///		the contents of this method with the code editor.
			/// </summary>
			private void InitializeComponent()
			{
				this.Load += new EventHandler(this.Page_Load);

			}
			#endregion
	

			private CA.TreeViewNode BuildNode(string name)
			{
				CA.TreeViewNode node = new CA.TreeViewNode();

				if (name.Length > 30)
					node.Text = name.Substring(0, 27) + "...";
				else
					node.Text = name;

				return node;
			}


			private CA.TreeViewNode BuildRootnode()
			{
				CA.TreeViewNode node = new CA.TreeViewNode();
				node.Text = "Root";
				node.DraggingEnabled = false;
				node.DroppingEnabled = true;
				node.EditingEnabled = false;
				node.ImageUrl = "folder.gif";
				node.Value = "-1";
				node.Expanded = true;
				node.ID = "-1";
				return node;
			}


			private void BuildSectionTree()
			{
				if (Tree == null)
					return;

				// Create root node
				CA.TreeViewNode rootNode = BuildRootnode();
				Tree.Nodes.Add(rootNode);
			
				BuildSectionTree(-1 , rootNode.Nodes);
			}


			private int BuildSectionTree(int sectionID, CA.TreeViewNodeCollection nodes)
			{
				ArrayList sections = ResLinkSection.GetSection(sectionID).Sections;

				CA.TreeViewNode node;
				foreach (Section sec in sections)
				{
					// Get a list of sections in this group
					node = BuildNode(sec.Name);
					node.DraggingEnabled = true;
					node.DroppingEnabled = true;
					node.EditingEnabled = false; 
					node.ID = String.Format("{0}", sec.SectionID);
					node.Value = String.Format("{0}", sec.SectionID);

					if (sec.IsActive)
					{
						node.ImageUrl = "folder.gif";
						node.Checked = true;
					}
					else
					{
						node.ImageUrl = "deletedFolder.gif";
						node.Checked = false;
					}

					nodes.Add(node);

					if (sec.SectionID == CSContext.Current.SectionID)
					{
						node.Expanded = true;
						if (CSContext.Current.SectionID < 0)
						{
							node.CssClass = Tree.SelectedNodeCssClass;
							node.HoverCssClass = Tree.SelectedNodeCssClass;
						}

					}

					int added = BuildSectionTree(sec.SectionID, node.Nodes);
				}

				return sections.Count;
			}

			[AjaxMethod(IncludeControlValuesWithCallBack=false)]
			public string ChangeSectionEnabled(int sectionID)
			{
				if( !IsAdministrator ) 
					return "-1";

				if(sectionID > 0)
				{
					ResLinkSection s = ResLinkSection.GetSection(sectionID);
					s.IsActive = !s.IsActive;
					ResLinkSection.Update(s); 

					ResLinkSection.ClearSectionCache(s.ParentID);
				}

				return string.Format("{0}", sectionID ) ;
			}

			protected void HandleXmlRequest(string value)
			{
				Match m = Regex.Match(value, AjaxQueryStringValuePattern);
				if (m != null)
				{
					CSContext.Current.SectionID = int.Parse(m.Groups[0].Value);

					CA.TreeView tree = new CA.TreeView();

					BuildSectionTree(CSContext.Current.SectionID , tree.Nodes);

					Page.Response.Clear();
					Page.Response.ContentType = "text/xml";
					Page.Response.Write(tree.GetXml());
					Page.Response.End();
				}
			}

			[AjaxMethod(IncludeControlValuesWithCallBack=false)]
			public string MoveSection(int sectionID ,int targetSectionID)
			{
				ResLinkSection section = ResLinkSection.GetSection(sectionID);

				// Determine if the user moved the Forum to another group and/or parent forum...
				//	or if this move was just a change in sort order in the same group & parent forum
				if (section.ParentID == targetSectionID)
				{
					// This is just a change in sort order. We can't do anything until we know
					//	the new index that the node was dropped in. So let client-side function know this...
					return "-1";
				}
				else
				{
					int oldParentSectionID = section.ParentID;
					//Need to check that the section that this section is being moved to is unique
					//do this using the app key
					if (targetSectionID < 0)
					{
						section.ParentID = 0;
					}
					else
					{
						section.ParentID = targetSectionID;
					}

					string formatedKey = string.Empty;
					ResLinkSection.GenerateAppKey(targetSectionID , section.Name ,out formatedKey);
					section.ApplicationKey = formatedKey;
				
					if (section.IsUniqueInCurrentContext())
					{
						ResLinkSection.Update(section);
					}
					else
					{
						return string.Format("-1^{0}^{1}", sectionID , oldParentSectionID);
					}
				}

				return string.Format("{0}^{1}",sectionID, targetSectionID) ;
			}

			[AjaxMethod(IncludeControlValuesWithCallBack=false)]
			public string AddSection(int sectionID, string name)
			{
				if(name.Trim() == string.Empty)
					return "-1";

				ResLinkSection s = new ResLinkSection();
			
				string formattedKey = null;
				ResLinkSection.GenerateAppKey(sectionID , name , out formattedKey);

				//Set remaining section settings
				s.ParentID = sectionID;
				s.Name = name;
				s.ApplicationKey = formattedKey;
				s.IsActive = false;
				s.SettingsID = CSContext.Current.SiteSettings.SettingsID;
				s.ApplicationType = (ApplicationType)ExApplicationType.ResLink;

				s.IsSearchable =  true;

				//Create The section
				s.SectionID = ResLinkSection.Add(s).SectionID;
			
				return string.Format("{0}^{1}^{2}",s.SectionID, name , sectionID) ;
			}

			[AjaxMethod(IncludeControlValuesWithCallBack=false)]
			public string DeleteSection(int sectionID)
			{
				if( !IsAdministrator ) 
					return "0";

				ResLinkSection s = ResLinkSection.GetSection(sectionID); 
				ResLinkSection.Delete(s);
				return string.Format("{0}", sectionID) ;
			}	

	}

}
